package db_sports

import (
	"github.com/agext/levenshtein"
	"gorm.io/gorm"
	"longmen/server/config/global"
	"longmen/server/pkg/db/mysql/models/models_sports"
	"sort"
	"time"
)

//模糊查找，获得赛事直播链接
func GetMatchLiveUrl(db *gorm.DB, home, away string) string {
	return ""
}

//模糊查找，获得赛事id
func GetMatchId(db *gorm.DB, home, away string) int64 {
	var data []*models_sports.MatchesSchedule
	// 获取当前日期和时间
	now := time.Now()
	// 获取今天零时时间
	zeroTime := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	err := db.Select("home,away,match_id").Where("match_time >= ? and match_time < ?", zeroTime.Unix(), zeroTime.Unix()+86400).Find(&data).Error
	if err != nil {
		global.Log.Errorf("err %v", err)
		return 0
	}
	sourceSlice := make(map[float64]int64)
	for _, v := range data {
		homeDistance := levenshtein.Match(home, v.Home, nil)
		homeDistance1 := levenshtein.Match(home, v.Away, nil)
		awayDistance := levenshtein.Match(away, v.Home, nil)
		awayDistance1 := levenshtein.Match(away, v.Away, nil)
		//global.Log.Debugf("homeDistance:%v,homeDistance1:%v,awayDistance:%v,awayDistance:%v", homeDistance, homeDistance1, awayDistance, awayDistance1)
		if (homeDistance == 1 || homeDistance1 == 1) && (awayDistance == 1 || awayDistance1 == 1) {
			return v.MatchId
		}

		if (homeDistance > 0 || homeDistance1 > 0) && (awayDistance > 0 || awayDistance1 > 0) {
			//global.Log.Debugf("home:%s, away:%s,dbhome:%s,dbaway:%s", home, away, v.Home, v.Away)
			//global.Log.Debugf("homeDistance:%v,homeDistance1:%v,awayDistance:%v,awayDistance:%v", homeDistance, homeDistance1, awayDistance, awayDistance1)
			tempSlice := []float64{homeDistance, homeDistance1, awayDistance, awayDistance1}
			sort.Float64s(tempSlice)
			global.Log.Debugf("得分:tempSlice:%v\n", tempSlice)
			sourceSlice[tempSlice[len(tempSlice)-1]] = v.MatchId
		}
	}
	if len(sourceSlice) < 1 {
		return 0
	}

	type Pair struct {
		Key   int64
		Value float64
	}
	pairs := make([]Pair, 0, len(sourceSlice))
	for k, v := range sourceSlice {
		pairs = append(pairs, Pair{v, k})
	}
	sort.Slice(pairs, func(i, j int) bool {
		return pairs[i].Value > pairs[j].Value
	})

	return pairs[0].Key
}

func GetLiveVideoStream(db *gorm.DB, matchId int32) string {
	data := &models_sports.MatchLive{}
	err := db.Select("stream,uhd_link,hd_link,sd_link,pc_link").Where("match_id = ?", matchId).First(data).Error
	if err != nil {
		global.Log.Errorf("GetLiveVideoStream err:%v", err)
		return ""
	}
	return data.Stream
}
